package org.kd.controller;
/**
 * 代号:隐无为 2017：厚溥
 * 文件名：LoginController.java
 * 创建人：柯栋
 * 日期：2018年2月25日
 * 修改人：
 * 描述：
 */


import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.kd.common.ResponseAPI;
import org.kd.common.base.controller.BaseController;
import org.kd.model.Emp;
import org.kd.model.DTO.EmpDTO;
import org.kd.service.EmpService;
import org.kd.utils.JsonReturnData;
import org.kd.utils.WebConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用途：登录模块
 */
@Controller
@RequestMapping("/loginController")
public class LoginController extends BaseController {
	@Autowired
	ResponseAPI responseAPI;
	@Autowired
	EmpService empService;
	@RequestMapping("/loginPage")
	public String loginPage() {
		return "loginPage";
	}

	@RequestMapping("/loginCheck")
	@ResponseBody
	public String loginCheck(Emp emp,HttpSession session) {
		JsonReturnData<String> jsonReturnData = new JsonReturnData<>(WebConstant.ERRORCODE, "登录失败");

		UsernamePasswordToken token = new UsernamePasswordToken(emp.getUsername(),emp.getPassword());
		Subject subject = SecurityUtils.getSubject();
		
		try {
			subject.login(token);
			session.setAttribute("user", empService.queryByOneParmWithTable(emp));
			jsonReturnData.setCode(WebConstant.SUCCESSCODE);
			jsonReturnData.setMsg("登录成功");
		} catch (Exception e) {
			jsonReturnData.setCode(WebConstant.PAGESUCCESSCODE);
			jsonReturnData.setMsg("账号登录失败");
		}finally {
			return  responseAPI.getJsonString(jsonReturnData);
		}
		
	}
	
	
	@RequestMapping("/main")
	public String main() {
		return "main";
	}
	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session){
		session.removeAttribute("user");
		return "loginPage";
	}
	
	@RequestMapping("/errorPage")
	public String errorPage() {
		return "errorPage";
	}
}
